<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016 杭州博也网络科技, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------


namespace Shop\Api;

use Common\Api\Api;
use Shop\Model\OrdersContactinfoModel;
use Shop\Model\OrdersItemModel;
use Shop\Model\OrdersModel;

class OrdersApi extends Api
{

    /**
     * 查询包含订单相关的信息，订单商品，
     */
    const QUERY_ALL_INFO = "Shop/Orders/queryAllInfo";
    /**
     * 假删除
     */
    const PRETEND_DELETE = "Shop/Orders/pretendDelete";
    /**
     * 添加
     */
    const COUNT = "Shop/Orders/count";


    const SUM="Shop/Orders/sum";
    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "Shop/Orders/queryNoPaging";
    /**
     * 添加
     */
    const ADD = "Shop/Orders/add";
    /**
     * 保存
     */
    const SAVE = "Shop/Orders/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Shop/Orders/saveByID";

    /**
     * 删除
     */
    const DELETE = "Shop/Orders/delete";

    /**
     * 查询
     */
    const QUERY = "Shop/Orders/query";
    /**
     * 查询一条数据
     */
    const GET_INFO = "Shop/Orders/getInfo";

    /**
     * 统计指定商品的月销量
     */
    const MONTHLY_SALES = "Shop/Orders/monthlySales";
    /**
     * 添加订单信息
     */
    const ADD_ORDER = "Shop/Orders/addOrder";
    /**
     * 更新订单状态
     */
    const SAVE_PAY_STATUS = "Shop/Orders/savePayStatus";

    /*
   * 查询买到的所有商品的订单信息
   * */
    const SELECT_SELL_ORDER = "Shop/Orders/selectSellOrder";


    /*
   * 查询买到的商品被购买的信息
   * */
    const ORDER_BUY = "Shop/Orders/order_buy";



    protected function _init()
    {
        $this->model = new OrdersModel();
    }


    /**
     *
     * 查询
     * @author hebidu <hebiduhebi@126.com>
     * @date  15/11/13 11:07
     * @copyright by itboye.com
     * @param $type
     * @param $uid
     * @param $page
     * @param $order
     * @param $params
     * @return array
     * @internal param $map
     */
    public function queryAllInfo($type,$uid,$page,$order,$params){

        //1. 设置支付状态
        if ($type == 1) {
            //待付款
            $where = ' and pay_status = '.OrdersModel::ORDER_TOBE_PAID;
        } elseif($type != 0) {
            //货到付款，在线已支付
            $where = ' and pay_status = '.OrdersModel::ORDER_PAID;
        }

        //2. 设置订单状态
        if($type == 1){
            //1. 等于待确认
            $where .= ' and order_status = '.OrdersModel::ORDER_TOBE_CONFIRMED;
        }elseif ($type == 2) {
            //1. 已发货
            $where .= ' and order_status = '.OrdersModel::ORDER_SHIPPED;
        }elseif($type == 3){
            $where .= ' and order_status = '.OrdersModel::ORDER_CANCEL;
        }elseif($type == 0){
            $where .= ' and  order_status != '.OrdersModel::ORDER_CANCEL;
        }

        $uid_str = " orders.uid = ".$uid;

        $list = $this->model->alias("orders")->join("LEFT JOIN __ORDERS_ITEM__ as item on item.order_code = orders.order_code")
            ->join("LEFT JOIN __ORDERS_CONTACTINFO__ as info on info.order_code = orders.order_code")
        ->field("orders.uid,info.contactname,orders.storeid,orders.order_code,orders.id,orders.price,orders.pay_status,orders.order_status,orders.createtime,orders.from,orders.brokerage_ratio,orders.tax_amount,orders.goods_amount,orders.discount_money,orders.pay_code,orders.pay_type,item.p_id as item_p_id,item.price as item_price,item.count,item.sku_desc,item.name,item.img")
            ->where($uid_str.$where) -> page($page['curpage'] . ',' . $page['size'])->order($order) ->select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where(' uid = '.$uid .$where) -> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));

    }

    /**
     * 统计指定商品的月销量
     * @param array|商品ID数组 $p_ids 商品ID数组
     * @return array
     */
    public function monthlySales(array $p_ids)
    {
        return $this->apiReturnSuc(0);
    }


    /**
     * 事务增加订单信息
     * @param $entity = array(
     *      'uid'=>购买人ID,
     *      'order_code'=>生成的订单编号
     *      'price'=>成交价格
     *      'post_price'=>运费价格
     *      'note'=>订单备注
     *      'storeid'=>店铺ID
     *      'IDCode'=>使用的IDcode
     *      'discount_money'=>该订单优惠的金额总数
     *      'tax_amount'=>税款，根据dt_tariff_code计算
     *      'from'=>订单来源
     *
     *      //订单包含的商品
     *      'items'=>array(
     *           'p_id'=>$vo['p_id'],  //商品ID
     *           'name' => $vo['name'], //商品名称
     *           'ori_price' => $vo['ori_price'],//商品原价
     *           'price' => $vo['price'],//商品成交价
     *           'img' => $vo['icon_url'], //商品图片
     *           'count' => $vo['count'],  //成交数量
     *           'sku_id' => $vo['sku_id'], //规格
     *           'sku_desc' => $vo['sku_desc'], //规格描述
     *           'createtime' => $currentTime, //创建时间
     *           'dt_tariff_code'=>$vo['dt_tariff_code'], //行邮税号
     *           'goodsUnit'=>$vo['goodsUnit'],  //计量单位编码
     *           'dt_origin_country'=>$vo['dt_origin_country'], //国别编码
     *           'weight'=>$vo['weight'], //商品单个毛重
     *      ),
     *
     *      //订单收货信息
     *      'contactname' => 'contactname',
     *       'order_code' => 'order_code',
     *       'mobile' => ['mobile'],
     *       'country' => ['country'],
     *       'province' => ['province'],
     *       'city' => ['city'],
     *       'area' => ['area'],
     *       'wxno' => ['wxno'],
     *       'detailinfo' => ['detailinfo'],
     *       'notes'=>''
     *      'id_card'=>身份证
     *
     * )
     * @return array
     */
    public function addOrder($entity)
    {

        $flag = true;
        $error = "";
        //1. 增加order表记录
        $order = array(
            'uid' => $entity['uid'],
            'order_code' => $entity['order_code'],
            'price' => $entity['price'],
            'post_price' => $entity['post_price'],
            'note' => $entity['note'],
            'pay_status'=>$entity['pay_status'],
            'comment_status'=>0,
            'storeid' => $entity['storeid'],
            'idcode'=>$entity['idcode'],
            'discount_money'=>$entity['discount_money'],
            'from'=>$entity['from'],
            'pay_balance' => $entity['pay_balance'],
            'pay_score' => $entity['pay_score'],
            'tax_amount'=>$entity['tax_amount'],
            'goods_amount'=>$entity['goods_amount'],
            'pay_type'=>$entity['pay_type'],
            'brokerage_ratio'=>$entity['brokerage_ratio'],
        );


        $result = $this->add($order);

//		addWeixinLog($result,'add order 订单 2');

        //$orderid = '';
        if ($result['status']) {
          //  $orderid = $result['info'];
            //2. 增加order_contactinfo记录
            $orderContactInfo = array(
                'uid' => $entity['uid'],
                'contactname' => $entity['contactname'],
                'order_code' => $entity['order_code'],
                'mobile' => $entity['mobile'],
                'country' => $entity['country'],
                'province' => $entity['province'],
                'city' => $entity['city'],
                'area' => $entity['area'],
                'wxno' => $entity['wxno'],
                'detailinfo' => $entity['detailinfo'],
                'notes'=>'',
                'postal_code'=>$entity['postal_code'],
                'id_card'=>$entity['id_card'],
            );

            $model = new OrdersContactinfoModel();
            $result = $model->create($orderContactInfo, 1);

            if ($result) {
                $result = $model->add();
                if ($result === FALSE) {
                    //新增失败
                    $flag = false;
                    $error = $model->getDbError();
                }

            } else {//自动验证失败
                $flag = false;
                $error = $model->getError();
            }

        } else {
            $flag = false;
            $error = $result['info'];
        }

        if ($flag) {
            //上面的都没有错误
            //3. 插入到orders_item表中
            $products = $entity['items'];
            $items_arr = array();
            $currentTime = time();
            foreach ($products as $vo) {
                $tmp = array(
                    'order_code' =>  $entity['order_code'],
                    'has_sku' => '0',
                    'p_id' => $vo['p_id'],
                    'name' => $vo['name'],
                    'ori_price' => $vo['ori_price'],
                    'price' => $vo['price'],
                    'img' => $vo['icon_url'],
                    'count' => $vo['count'],
                    'sku_id' => $vo['sku_id'],
                    'sku_desc' => $vo['sku_desc'],
                    'createtime' => $currentTime,
//                    'pay_status'=>0,
                    'goodsUnit'=>$vo['goodsUnit'],
                    'dt_origin_country'=>$vo['dt_origin_country'],
                    'weight'=>$vo['weight'],
                    'tax_rate'=>$vo['taxrate'],
                );

                if (intval($vo['has_sku']) == 1) {

                    if (!empty($vo['sku_desc']['icon_url'])) {
                        $tmp['img'] = $vo['sku_desc']['icon_url'];
                    }

                }

                array_push($items_arr, $tmp);
            }

            $model = new OrdersItemModel();

            $result = $model->addAll($items_arr);

            if ($result === false) {
                //新增失败
                $flag = false;
                $error = $model->getDbError();
            }

        }

        if ($flag) {
            return $this->apiReturnSuc( $entity['order_code']);
        } else {
            return $this->apiReturnErr($error);
        }

    }


    /**
     * 设置支付状态
     * @param $map
     * @param $paystatus
     * @return array
     * @internal param 数组 $orderid
     */
    public function savePayStatus($map, $paystatus)
    {
        $result = $this->model->where($map)->lock(true)->save(array('pay_status' => $paystatus));
        if ($result === FALSE) {
            $error = $this->model->getDbError();
            return $this->apiReturnErr($error);
        } else {
            return $this->apiReturnSuc($result);
        }
    }


    /*
   * 查询出买家买到的所有商品
   * */
    public function selectSellOrder($map,$field = false){
        $query = $this->model->where($map);
        $result = $query->alias('o')->join('LEFT JOIN itboye_orders_item i on o.order_code = i.order_code')->field($field)->order('o.createtime desc')->select();
        if ($result === FALSE) {
            $error = $this->model->getDbError();
            return $this->apiReturnErr($error);
        } else {
            return $this->apiReturnSuc($result);
        }
    }


    /*
 * 查询出商品所有的买家
 * */
    public function order_buy($map){
        $field='nm.name,o.updatetime';
        $result = $this->model->alias('o')
            ->join('JOIN itboye_orders_item i on o.order_code = i.order_code')
            ->join('LEFT JOIN itboye_new_member nm on o.uid = nm.id')
            ->where($map)
            ->field($field)->order('o.createtime desc')
            ->select();
        if ($result === FALSE) {
            $error = $this->model->getDbError();
            return $this->apiReturnErr($error);
        } else {
            return $this->apiReturnSuc($result);
        }
    }


}
